package com.alex.wechat.mp.message.autoresp.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.wechat.mp.config.WxConsts;
import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.message.autoresp.entity.WxAutoResponse;
import com.alex.wechat.mp.message.autoresp.service.WxAutoResponseServiceI;
import com.alex.wechat.mp.message.news.entity.WxNewsTemplate;
import com.alex.wechat.mp.message.news.service.WxNewsTemplateServiceI;
import com.alex.wechat.mp.message.text.entity.WxTextTemplate;
import com.alex.wechat.mp.message.text.service.WxTextTemplateServiceI;

/**
 * 自动回复关键字
 * 
 */
@Controller
@RequestMapping("/wxAutoResponseController")
public class WxAutoResponseController {

  private static final Logger logger = LoggerFactory.getLogger(WxAutoResponseController.class);

  @Autowired
  private SystemService systemService;
  @Autowired
  private WxAutoResponseServiceI autoResponseService;
  @Autowired
  private WxTextTemplateServiceI textTemplateService;
  @Autowired
  private WxNewsTemplateServiceI newsTemplateService;

  /*
   * 转向列表
   */
  @RequestMapping(params = "list")
  public ModelAndView list() {
    return new ModelAndView("com/gomore/wechat/mp/message/autoresp/autoresponselist");
  }

  /**
   * 消息自动回复
   * 
   * @param autoResponse
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "datagrid")
  @ResponseBody
  public void datagrid(WxAutoResponse autoResponse, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {
    CriteriaQuery cq = new CriteriaQuery(WxAutoResponse.class, dataGrid);
    cq.eq("accountId", WxContext.getOriginalId());
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, autoResponse);
    this.autoResponseService.getDataGridReturn(cq, true);
    TagUtil.datagrid(response, dataGrid);
  }

  /**
   * 删除信息
   * 
   * @param autoResponse
   * @param req
   * @return
   */
  @RequestMapping(params = "del")
  @ResponseBody
  public AjaxJson del(WxAutoResponse autoResponse, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    autoResponse = this.autoResponseService.getEntity(WxAutoResponse.class, autoResponse.getId());
    this.autoResponseService.delete(autoResponse);
    String message = "删除信息数据成功！";
    systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    j.setMsg(message);
    return j;

  }

  /**
   * 自动回复消息
   * 
   * @param req
   * @return
   */
  @RequestMapping(params = "addOrUpdate")
  public ModelAndView addOrUpdate(HttpServletRequest req) {
    String id = req.getParameter("id");
    req.setAttribute("id", id);

    List<WxTextTemplate> textList = textTemplateService
        .getAllByAccountId(WxContext.getOriginalId());
    List<WxNewsTemplate> newsList = newsTemplateService
        .getAllByAccountId(WxContext.getOriginalId());
    req.setAttribute("textList", textList);
    req.setAttribute("newsList", newsList);

    if (StringUtil.isNotEmpty(id)) {
      WxAutoResponse autoResponse = this.autoResponseService.getEntity(WxAutoResponse.class, id);
      if (autoResponse != null) {
        req.setAttribute("msgType", autoResponse.getMsgType());
        req.setAttribute("keyWord", autoResponse.getKeyWord());
        req.setAttribute("templateId", autoResponse.getTemplateId());
        req.setAttribute("templateName", autoResponse.getTemplateName());
      }
    }
    return new ModelAndView("com/gomore/wechat/mp/message/autoresp/autoresponseinfo");
  }

  /**
   * 保存关键字修改
   * 
   * @param autoResponse
   * @param req
   * @return
   */
  @RequestMapping(params = "doSave")
  @ResponseBody
  public AjaxJson doSave(WxAutoResponse autoResponse, HttpServletRequest req) {

    String templateName = "";
    AjaxJson j = new AjaxJson();
    String id = autoResponse.getId();
    if (StringUtil.isNotEmpty(id)) {
      WxAutoResponse tempAutoResponse = this.autoResponseService.getEntity(WxAutoResponse.class,
          autoResponse.getId());
      // 获取模板文名字
      templateName = getTempName(autoResponse.getMsgType(), autoResponse.getTemplateId());
      autoResponse.setTemplateName(templateName);

      String message = "修改关键字回复成功！";
      try {
        MyBeanUtils.copyBeanNotNull2Bean(autoResponse, tempAutoResponse);
        this.autoResponseService.saveOrUpdate(tempAutoResponse);
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
      } catch (Exception e) {
        logger.error("", e);
        j.setSuccess(false);
        message = "保存关键字失败: " + e.getMessage();
      }
      j.setMsg(message);
    } else {
      autoResponse.setCreateDate(new Date());
      String templateId = autoResponse.getTemplateId();
      String msgType = autoResponse.getMsgType();
      templateName = getTempName(msgType, templateId);
      autoResponse.setTemplateName(templateName);

      if (WxContext.hasWxAccount()) {
        autoResponse.setAccountId(WxContext.getOriginalId());
        this.autoResponseService.save(autoResponse);
      } else {
        j.setSuccess(false);
        j.setMsg("请添加一个公众帐号。");
      }
    }
    return j;
  }

  /**
   * 获取模板文件名字
   * 
   * @param msgType
   * @param templateId
   * @return
   */
  private String getTempName(String msgType, String templateId) {
    String templateName = "";
    if (WxConsts.XML_MSG_TEXT.equals(msgType)) {
      WxTextTemplate textTemplate = this.autoResponseService.getEntity(WxTextTemplate.class,
          templateId);
      if (textTemplate != null) {
        templateName = textTemplate.getTemplateName();
      }

    } else if (WxConsts.XML_MSG_NEWS.equals(msgType)) {
      WxNewsTemplate newsTemplate = this.autoResponseService.getEntity(WxNewsTemplate.class,
          templateId);
      if (newsTemplate != null) {
        templateName = newsTemplate.getTemplateName();
      }
    }
    return templateName;
  }

}